import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import { NewAccountHome } from '../../../components/common/newAccountHome';
import StockService from "../_common/service";
import { CommonDialog } from '../../../components/common/Dialog';
import { NavigationEvents } from 'react-navigation';

const scale = GLOBAL.SCALE;

export class QhPostponeListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '泉化担保日延期申请审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			modalVisible: false,
			refreshIcon: false, // 下拉刷新图标
			listData: [], // 列表数据
			refuseModalVisible: false,
			choice: {}
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数

		this.pageParams = { // TODO
			pageNo: 1,
			pageSize: 10
		}
		this.titleData = [];
	}

	componentWillMount() {
		this._getData();
	}

	//获取头部数据
	_getTitle = async () => {
		let titleData = await StockService.storeTitle(this.pageParams);
		if (titleData && titleData.length) {
			if (titleData.length === 1) this.pageParams.corpId = null; // 如果审批最后一条,移除上一次id
			if (this.pageParams.corpId && !titleData.some(item => item.corpId === this.pageParams.corpId)) {
				this.pageParams.corpId = null;
			}
			this.pageParams.corpId = this.pageParams.corpId || titleData[0].corpId;
			this.titleData = titleData || [];
		}
	}


	//获取列表数据
	_getData = async (topRefresh) => {
		if (!topRefresh) { //代表头部 必须刷新头部
			await this._getTitle();
		}

		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let res = await StockService.qhPostponeList(this.pageParams);
		console.log('页面获取-参数', this.pageParams);
		console.log('页面获取-res', res)
		if (res && res.rows) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error',
			})
		}

	}


	// 下拉更新函数
	_isLoadRefresh = async () => {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this._getData(true);
	}

	// 刷新
	_reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this._getData(true);
	}

	// 上拉更新函数
	_onEndReached = async () => {
		if (this.pageParams.pageNo < this.totalPage) {
			this.pageParams.pageNo++;
			this.reload = false;
			this._getData(true);
		}
	}

	// 查看备注
	_showRemark = (alertRemark) => {
		this.alertRemark = alertRemark;
		this.setState({
			modalVisible: true
		})
	}





	_audit = async () => {
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const responseData = await StockService.qhChangeAuto({
			auditResult: this.isAgreed,
			remark: this.remark, // 填写
			corpId: this.pageParams.corpId,
			changeId: this.changeId,
			changeType: this.changeType
		})
		this.setState({ loaded: false });
		console.log('responseData', responseData)
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == 0) ? '驳回成功' : '审批成功').then(() => {
				this.requesting = false;
				this._getData();
			})
		} else {
			this.requesting = false;
		}
	}

	_pass(data) {
		let { changeId, changeType } = data;
		this.isAgreed = 1;
		this.remark = '';
		this.changeId = changeId;
		this.changeType = changeType;
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse(data) {
		let { changeId, changeType } = data;
		this.isAgreed = 0;
		this.remark = '';
		this.changeId = changeId;
		this.changeType = changeType;
		this.setState({
			refuseModalVisible: true
		})
	}

	// 列表
	_renderListItem = (data) => {
		const { remark, companyName, createTime, orderId, changeId, changeType, inStockNoticeItemVOList, salesmanName, organName } = data.item;
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => {
				this.props.navigation.navigate('QhPostponeDetialsPage', {
					changeId,
					choice: this.state.choice,
					callback: () => this.reloadPage()
				})
			}} style={{ marginBottom: 18 * scale, paddingHorizontal: 16 * scale }}>
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
					<Text style={styles.titleText}>{companyName || '-'}</Text>
					<Text style={styles.titleText}>{(createTime || '-').substring(0, 16)}</Text>
				</View>
				<View style={{ backgroundColor: '#fff', borderRadius: 4 * scale }}>
					<View style={styles.billNumWrap}>
						<Text style={styles.commonTitle}>{orderId || '-'}  |  {changeId || '-'} </Text>
					</View>
					<View style={styles.body}>
						{
							inStockNoticeItemVOList && inStockNoticeItemVOList.length && inStockNoticeItemVOList.map((item, index) => {
								return (
									<View key={index}>
										<View style={styles.itemBox}>
											<Text style={[styles.itemTitle, styles.itemColor]}>担保日期</Text>
											<View style={styles.itemValueBox}>
												<Text style={[styles.itemValue, styles.textOld]}>{item.warrantDateBrfore}</Text>
												<Text style={styles.arrow}>—></Text>
												<Text style={[styles.itemValue, styles.textNew]}>{item.warrantDateAfter}</Text>
											</View>
										</View>
										{
											changeType === "inStockNotice" ? <View style={styles.itemBox}>
												<Text style={[styles.itemTitle, styles.itemColor]}>预计收货日期</Text>
												<View style={styles.itemValueBox}>
													<Text style={[styles.itemValue, styles.textOld]}>{item.expectExeDateBrfore}</Text>
													<Text style={styles.arrow}>—></Text>
													<Text style={[styles.itemValue, styles.textNew]}>{item.expectExeDateAfter}</Text>
												</View>
											</View> : <View style={styles.itemBox}>
													<Text style={[styles.itemTitle, styles.itemColor]}>有效出库日期</Text>
													<View style={styles.itemValueBox}>
														<Text style={[styles.itemValue, styles.textOld]}>{item.outStockEndDateBrfore}</Text>
														<Text style={styles.arrow}>—></Text>
														<Text style={[styles.itemValue, styles.textNew]}>{item.outStockEndDateAfter}</Text>
													</View>
												</View>
										}

									</View>
								)
							})
						}
						<View style={styles.itemBox}>
							<Text style={[styles.itemTitle, styles.itemColor]}>备注</Text>
							<TouchableOpacity style={styles.findNote} onPress={() => { this._showRemark(remark); }}>
								<Text style={styles.findText}>[查看备注]</Text>
							</TouchableOpacity>
						</View>
						<View style={styles.itemBox}>
							<Text style={[styles.itemTitle, styles.itemColor]}>业务员</Text>
							<Text style={styles.itemYw}>{salesmanName} | {organName}</Text>
						</View>
					</View>
					<View style={styles.buttonBox}>
						<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
							this._pass({ changeId, changeType });
						}}>
							<Text style={styles.buttonPassText}>通过</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
							this._refuse({ changeId, changeType });
						}}>
							<Text style={styles.buttonRefuseText}>驳回</Text>
						</TouchableOpacity>
					</View>
				</View>

			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, choice, modalVisible } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents
					onWillFocus={({ action }) => {
						this._getData();
					}}
				/>
				{this.titleData.length > 1 ?
					<NewAccountHome
						fn={(val) => { this.pageParams.corpId = this.titleData[val].corpId; this.pageParams.pageNo == '1'; this._getData(); }}
						options={this.titleData}
						choice={choice} />
					: null}
				{
					status == 'data' ? (
						<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={this._isLoadRefresh}
								onEndReached={this._onEndReached}
								onEndReachedThreshold={0.1}
							/>
						</View>) : <View style={{ flex: 1 }}>
							<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this._reloadPage} />
						</View>
				}
				<CommonDialog modalVisible={modalVisible} title={"提示"} text={this.alertRemark} onClosePress={() => { this.setState({ modalVisible: false }) }} />
				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	billNumWrap: {
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		flexDirection: 'column',
		alignItems: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 16 * scale,
		paddingBottom: 10 * scale
	},
	commonTitle: {
		flex: 1,
		color: '#030303',
		fontSize: 12 * scale,
		minWidth: 64 * scale,
	},
	buttonPass: {
		width: 68 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 68 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	titleText: {
		color: '#848A96',
		marginBottom: 6 * scale,
		fontSize: 12 * scale
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginTop: 18 * scale
	},
	body: {
		paddingHorizontal: 12 * scale,
		marginTop: 10 * scale
	},
	itemBox: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 35 * scale
	},
	itemColor: {
		color: '#000',
		opacity: 0.7,
		fontSize: 12 * scale
	},
	itemTitle: {
		width: '30%',
	},
	itemValue: {
		fontSize: 13 * scale,
		color: '#000'
	},
	itemValueBox: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	textNew: {
		color: "#CA0202"
	},
	findNote: {
		paddingVertical: 5 * scale,
		paddingRight: 8 * scale
	},
	findText: {
		fontSize: 13 * scale,
		fontWeight: 'bold',
		color: style.color.themeColor
	},
	itemYw: {
		fontSize: 13 * scale,
		color: '#000'
	},
	arrow: {
		fontSize: 13 * scale,
		color: "#CA0202",
		paddingHorizontal: 10 * scale
	}

})